package cn.iocoder.yudao.module.bpm.framework.flowable.core.ruleCalculate;

import cn.iocoder.yudao.module.bpm.service.definition.BpmModelService;
import cn.iocoder.yudao.module.bpm.service.task.BpmProcessInstanceService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.ExtensionElement;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.context.annotation.Lazy;
import org.springframework.expression.Expression;
import org.springframework.stereotype.Component;
import cn.iocoder.yudao.framework.common.util.spel.ExpressionEvaluator;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程分支的执行判断类
 * @Author wangzhichao
 * @Date 2024-08-05 17:35
 */
@Component("bpmBranchRuleSpelCalculate")
@Slf4j
@AllArgsConstructor
public class BpmBranchRuleSpelCalculate {

    private final ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator();

    @Resource
    @Lazy
    private BpmProcessInstanceService processInstanceService;
    @Resource
    @Lazy
    private BpmModelService bpmModelService;

    public Boolean calculate(DelegateExecution execution,String conditionExpression){
        log.info("开始计算分支规则，calculate.....",conditionExpression);
        //获取当前节点
        FlowElement currentFlowElement = execution.getCurrentFlowElement();
        log.debug("节点：{}",currentFlowElement.getName());
        //流程实例Id
        String processInstanceId = execution.getProcessInstanceId();
        ProcessInstance processInstance = processInstanceService.getProcessInstance(processInstanceId);
        // 获取到部署的ID
        String deploymentId = processInstance.getDeploymentId();
        // 根据获取到任务id和部署的id，获取规则配置的信息，然后计算出相应的人员
        log.debug("部署id：{}",deploymentId);

        Map<String, Object> processVariables = processInstance.getProcessVariables();
        Map variables = new HashMap<>();
        variables.putAll(processVariables);

        Expression exp = expressionEvaluator.parseExpression(unescapeSpelCalculateStr(conditionExpression));
        Boolean res =  exp.getValue(variables,Boolean.class);

        return res ;
    }


    private String unescapeSpelCalculateStr(String str) {
        str = str.replace("&apos;", "'");
        str = str.replace("&quot;", "\"");
        return str;
    }
}
